package com.xuerhua.yxt.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xuerhua.yxt.dao.SchoolInfoMapper;
import com.xuerhua.yxt.model.SchoolInfo;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.SchoolQueryVO;
import com.xuerhua.yxt.service.ISchoolInfoService;
import com.xuerhua.yxt.wechat.utils.WechatModel;
import com.xuerhua.yxt.wechat.utils.WechatUtils;

@Service("schoolInfoService")
public class SchoolInfoServiceImpl implements ISchoolInfoService {

	@Autowired
	private SchoolInfoMapper schoolInfoMapper;
	
	@Override
	public int insertSelective(SchoolInfo record) {
		return schoolInfoMapper.insertSelective(record);
	}

	@Override
	public SchoolInfo selectByPrimaryKey(Integer id) {
		return schoolInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(SchoolInfo record) {
		return schoolInfoMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<SchoolInfo> selectListByParam(SchoolInfo record) {
		return schoolInfoMapper.selectListByParam(record);
	}

	@Override
	public List<SchoolInfo> selectListByPage(Page<SchoolInfo> page) {
		return schoolInfoMapper.selectListByPage(page);
	}

	@Override
	public List<SchoolInfo> selectSchoolList(SchoolQueryVO vo) {
		return schoolInfoMapper.selectSchoolList(vo);
	}

	@Override
	public SchoolInfo queryInitWechatByDomainUrl(String domainUrl) {
		SchoolInfo school = schoolInfoMapper.selectByDomainUrl(domainUrl);
		return refreshInitWechat(school);
	}

	@Override
	public SchoolInfo queryInitWechatBySchoolId(Integer schoolId) {
		SchoolInfo school = schoolInfoMapper.selectByPrimaryKey(schoolId);
		return refreshInitWechat(school);
	}

	@Override
	public SchoolInfo refreshInitWechat(SchoolInfo school) {
		if(school == null) {
			return null;
		}
		if(school.getAccessExpireIn() != null && school.getAccessExpireIn() > new Date().getTime()) {
			return school;
		}
		WechatModel model = WechatUtils.getAccessToken(school.getAppid(), school.getAppsecret());
		school.setAccessToken(model.getAccessToken());
		school.setJsapiToken(model.getJsapiTicket());
		school.setAccessExpireIn(System.currentTimeMillis() + (model.getAccessExpiresIn() - 900) * 1000);
		school.setJsapiExpireIn(System.currentTimeMillis() + (model.getAccessExpiresIn() - 600) * 1000);
		schoolInfoMapper.updateByPrimaryKeySelective(school);
		return school;
	}

}
